package api

import (
	"fmt"

	"gitee.com/krio/grpc-gin-client/core/lib"

	"github.com/gin-gonic/gin"
	"github.com/opentracing/opentracing-go"
	zkOt "github.com/openzipkin-contrib/zipkin-go-opentracing"
	"github.com/openzipkin/zipkin-go"
	"github.com/openzipkin/zipkin-go/reporter"
	zkHttp "github.com/openzipkin/zipkin-go/reporter/http"
)

var zkTracer opentracing.Tracer

const (
	serviceName = "zipkin_gin_client"                  // TODO
	zipkinAddr  = "http://127.0.0.1:9411/api/v2/spans" // TODO
)

// InitZipkinTracer init 链路追踪
func InitZipkinTracer() (reporter.Reporter, error) {
	reporter := zkHttp.NewReporter(zipkinAddr)
	endpoint, err := zipkin.NewEndpoint(serviceName, fmt.Sprintf("localhost:%d", lib.C.Gin.Port))
	if err != nil {
		return nil, err
	}
	nativeTracer, err := zipkin.NewTracer(reporter, zipkin.WithLocalEndpoint(endpoint))
	if err != nil {
		return nil, err
	}
	zkTracer = zkOt.Wrap(nativeTracer)
	opentracing.SetGlobalTracer(zkTracer)

	return reporter, nil
}

// Zipkin 将tracer注入到gin的中间件中
func Zipkin(c *gin.Context) {
	span := zkTracer.StartSpan(c.FullPath())
	defer span.Finish()
	c.Next()
}
